import client from '../db.ts'
/**
 * 用户接口
 */
// 根据id获取
const getById = async(id: number) => {
  return await client.query(`select * from user WHERE id=${id}`)
}
// 主页
export const Home = ({ response }: { response: any }) => {
  response.body = 'WELCOME MY SERVER'
}
// 查询列表
export const GetUsers = async({ response }: { response: any }) => {
  const result = await client.query('select * from user')
  response.body = { collection: result }
}
// 查询单个
export const GetUser = async({ response, params }: { response: any, params: any }) => {
  const id = parseInt(params.id)
  if (!id) {
    response.status = 400
    response.body = { error: 'Id must be have' }
    return
  }
  const result = await getById(id)
  if (!result) {
    response.status = 404
    response.body = { error: `User ${id} not found` }
    return
  }
  response.body = { document: result }
}
// 新增
export const CreateUser = async({ response, request }: { response: any, request: any }) => {
  if (!request.hasBody) {
    response.status = 400
    response.body = { error: 'Request body cannot be empty' }
    return
  }
  const { nickName, gender } = (await request.body(true)).value
  if (!nickName || !gender) {
    response.status = 400
    response.body = { error: 'Invalid payload is provided' }
    return
  }
  const { lastInsertId } = await client.execute(`INSERT INTO user (nickname, gender) VALUES ('${nickName}', ${parseInt(gender)})`)
  const result = await getById(lastInsertId || 0)
  response.status = 201
  response.body = { document: result }
}
// 修改
export const UpdateUser = async({ response, request, params }: { response: any, request: any, params: any }) => {
  const id = parseInt(params.id)
  if (!id || !request.hasBody) {
    response.status = 400
    response.body = { error: 'Invalid request' }
    return
  }
  const { nickName, gender } = (await request.body(true)).value
  if (!nickName || !gender) {
    response.status = 400
    response.body = { error: 'Invalid payload is provided' }
    return
  }
  await client.execute(`UPDATE user SET nickName='${nickName}', gender=${parseInt(gender)} WHERE id=${id}`)
  const result = await getById(id)
  if (!result) {
    response.status = 404
    response.body = { error: `User ${id} not found` }
  }
  response.status = 200
  response.body = { document: result }
}
// 删除
export const DeleteUser = async({ response, params }: { response: any, params: any }) => {
  const id = parseInt(params.id)
  if (!id) {
    response.status = 400
    response.body = { error: 'Id must be have' }
    return
  }
  await client.execute(`DELETE FROM user WHERE id=${id}`)
  response.status = 204
}